const { Verification, User } = require('../models');

exports.verifyUser = async (req, res) => {
    try {
        const { realName, idNumber, idCardFront, idCardBack, signature } = req.body;
        const userId = req.user.userinfo.id;

        // 检查用户是否已认证
        const existingVerification = await Verification.findOne({ userId });
        if (existingVerification) {
            return res.status(400).json({
                success: false,
                message: '用户已认证'
            });
        }

        // 创建认证记录
        const verification = await Verification.create({
            userId,
            realName,
            idNumber,
            idCardFront,
            idCardBack,
            signature
        });

        // 更新用户的认证状态
        await User.findByIdAndUpdate(userId, {
            isVerified: true,
            verification: verification._id
        });

        res.status(201).json({
            success: true,
            message: '实名认证提交成功，等待审核',
            data: verification
        });

    } catch (error) {
        console.error('实名认证错误:', error);
        res.status(500).json({
            success: false,
            message: '实名认证失败',
            error: error.message
        });
    }
};

// 添加获取用户认证状态的方法
exports.getVerificationStatus = async (req, res) => {
    try {
        const userId = req.user.userinfo.id;
        const user = await User.findById(userId).populate('verification');

        res.status(200).json({
            success: true,
            data: {
                isVerified: user.isVerified,
                verification: user.isVerified ? user.verification : null
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取认证状态失败',
            error: error.message
        });
    }
}; 